import React, { memo, useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Progress, Alert } from 'antd';
import { ThunderboltOutlined, DatabaseOutlined, ClockCircleOutlined } from '@ant-design/icons';

interface PerformanceMetrics {
  renderTime: number;
  memoryUsage: number;
  componentCount: number;
  lastUpdate: number;
}

export const PerformanceDashboard: React.FC = memo(() => {
  const [metrics, setMetrics] = useState<PerformanceMetrics>({
    renderTime: 0,
    memoryUsage: 0,
    componentCount: 0,
    lastUpdate: Date.now()
  });

  useEffect(() => {
    const measurePerformance = () => {
      const now = Date.now();
      
      // 测量内存使用（如果支持）
      const memoryInfo = (performance as any).memory;
      const memoryUsage = memoryInfo ? memoryInfo.usedJSHeapSize / 1024 / 1024 : 0;
      
      // 组件计数（简化版）
      const componentCount = document.querySelectorAll('[data-reactroot] *').length;
      
      setMetrics(prev => ({
        ...prev,
        memoryUsage,
        componentCount,
        lastUpdate: now
      }));
    };

    // 定期更新性能指标
    const interval = setInterval(measurePerformance, 5000);
    measurePerformance(); // 立即执行一次

    return () => clearInterval(interval);
  }, []);

  const getMemoryStatus = () => {
    if (metrics.memoryUsage < 50) return { status: 'success', text: '良好' };
    if (metrics.memoryUsage < 100) return { status: 'warning', text: '一般' };
    return { status: 'exception', text: '偏高' };
  };

  const getRenderStatus = () => {
    if (metrics.renderTime < 100) return { status: 'success', text: '优秀' };
    if (metrics.renderTime < 200) return { status: 'warning', text: '良好' };
    return { status: 'exception', text: '需优化' };
  };

  const memoryStatus = getMemoryStatus();
  const renderStatus = getRenderStatus();

  return (
    <Card title="性能监控面板" size="small">
      <Row gutter={16}>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="内存使用"
              value={metrics.memoryUsage}
              suffix="MB"
              precision={1}
              prefix={<DatabaseOutlined />}
              valueStyle={{ color: memoryStatus.status === 'success' ? '#3f8600' : memoryStatus.status === 'warning' ? '#faad14' : '#cf1322' }}
            />
            <Progress 
              percent={Math.min(100, (metrics.memoryUsage / 200) * 100)} 
              status={memoryStatus.status as any}
              size="small"
              format={() => memoryStatus.text}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="渲染时间"
              value={metrics.renderTime}
              suffix="ms"
              precision={0}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: renderStatus.status === 'success' ? '#3f8600' : renderStatus.status === 'warning' ? '#faad14' : '#cf1322' }}
            />
            <Progress 
              percent={Math.min(100, (metrics.renderTime / 300) * 100)} 
              status={renderStatus.status as any}
              size="small"
              format={() => renderStatus.text}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="DOM节点数"
              value={metrics.componentCount}
              prefix={<ThunderboltOutlined />}
              valueStyle={{ color: metrics.componentCount > 1000 ? '#cf1322' : '#3f8600' }}
            />
          </Card>
        </Col>
      </Row>
      
      {metrics.memoryUsage > 100 && (
        <Alert
          message="内存使用偏高"
          description="当前内存使用量较高，建议刷新页面或检查是否存在内存泄漏。"
          type="warning"
          showIcon
          style={{ marginTop: 16 }}
        />
      )}
    </Card>
  );
});

PerformanceDashboard.displayName = 'PerformanceDashboard';

export default PerformanceDashboard;